/*
 * Copyright 2025 The JA-SIG Collaborative. All rights reserved. distributed with this file and
 * available online at
 */
package com.lap.auth.application.region.assembler;

import com.github.stuxuhai.jpinyin.PinyinException;
import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import com.lap.auth.application.region.command.CreateRegionCmd;
import com.lap.auth.application.region.command.UpdateRegionCmd;
import com.lap.auth.application.region.dto.RegionDto;
import com.lap.auth.domain.region.Region;
import com.lap.auth.domain.shared.tools.BaseConverter;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Mapper(componentModel = "spring")
public interface RegionAssembler extends BaseConverter {
  Logger log = LoggerFactory.getLogger(RegionAssembler.class);

  @Mapping(target = "code", source = "name", qualifiedByName = "toPinyin")
  Region toDomain(CreateRegionCmd cmd);

  @Mapping(target = "code", source = "cmd.name", qualifiedByName = "toPinyin")
  Region toDomain(Integer id, UpdateRegionCmd cmd);

  @Mapping(target = "pidPaths", source = "pidPath")
  RegionDto toDto(Region region);

  List<RegionDto> toDtoList(List<Region> list);

  @Named("toPinyin")
  default String toPinyin(String name) {
    if (StringUtils.isNotBlank(name)) {
      try {
        return PinyinHelper.convertToPinyinString(name, " ", PinyinFormat.WITHOUT_TONE);
      } catch (PinyinException e) {
        log.warn("Pinyin failure,name:{}message:{}", name, e.getLocalizedMessage());
      }
    }
    return "";
  }
}
